package com.incom.log.appender.redis;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.spi.LoggingEvent;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisMqAppender extends AppenderSkeleton {
	
	private static JedisPool jedisPool;
	
	private String service = "service";
	
	private String host = "localhost";
	
    private int port = 6379;
    
    private String password = null;
    
    private String key = "log4j-log";
    
    private int dbIndex = 0;
    
    private int timeout = 10000;
	
	public RedisMqAppender() {

	}
	
	@Override
	public void close() {

	}

	@Override
	public boolean requiresLayout() {
		return true;
	}

	@Override
	protected void append(LoggingEvent event) {
		String log = "[" + service + "] " + this.layout.format(event);
		try {
			Jedis jedis = jedisPool.getResource();
			try {
				jedis.auth(password);
				jedis.select(dbIndex);
				jedis.rpush(key, log);
			} finally {
				jedis.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void activateOptions() {
		super.activateOptions();
		JedisPoolConfig poolConfig = new JedisPoolConfig();
		if(password != null && password.trim().length() > 0) {
			jedisPool = new JedisPool(poolConfig, host, port, timeout);
		} else {
			jedisPool = new JedisPool(poolConfig, host, port, timeout, password.trim());
		}
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public int getDbIndex() {
		return dbIndex;
	}

	public void setDbIndex(int dbIndex) {
		this.dbIndex = dbIndex;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}

	public String getService() {
		return service;
	}

	public void setService(String service) {
		this.service = service;
	}
	
}
